package com.dragon.aipictures.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.aipictures.Exception.BusinessException;
import com.dragon.aipictures.Exception.StateCode;
import com.dragon.aipictures.domain.Enum.UserRoleEnum;
import com.dragon.aipictures.domain.dto.request.UserQueryRequest;
import com.dragon.aipictures.domain.dto.request.user.UserLoginRequest;
import com.dragon.aipictures.domain.dto.request.user.UserRegisterRequest;
import com.dragon.aipictures.domain.entity.User;
import com.dragon.aipictures.domain.vo.user.LoginUserVO;
import com.dragon.aipictures.domain.vo.user.UserVO;
import com.dragon.aipictures.manager.auth.StpKit;
import com.dragon.aipictures.mapper.userMapper;
import com.dragon.aipictures.service.userService;
import com.dragon.aipictures.util.ThrowUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.dragon.aipictures.constant.UserConstant.USER_LOGIN_CODE;

/**
* @author 20390
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-01-21 10:08:38
*/
@Service
public class userServiceImpl extends ServiceImpl<userMapper, User>
    implements userService {
    @Resource
    private userMapper userMapper;



    @Override
    public boolean userRegister(UserRegisterRequest userRegisterRequest, HttpServletRequest request){
     String account = userRegisterRequest.getAccount();
     String password = userRegisterRequest.getPassword();
     String checkPassword = userRegisterRequest.getCheckPassword();


        if(ObjectUtil.isEmpty(account)||ObjectUtil.isEmpty(password)||ObjectUtil.isEmpty(checkPassword)||ObjectUtil.isEmpty(request)){
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
//        如果密码长度小于8位，报错
        ThrowUtil.throwIf(password.length()<8,StateCode.PARAMS_ERROR,"密码长度不能小于8位");

//        如果账号长度小于4位，报错
        ThrowUtil.throwIf(account.length()<4,StateCode.PARAMS_ERROR,"账号长度不能小于4位");
//        如果两次密码输入不一致，报错
        ThrowUtil.throwIf(!StrUtil.equals(password,checkPassword),StateCode.PARAMS_ERROR,"两次密码输入不一致");

//        如果账号已经重复，报错
        String encryptPassword=getEncryptPassword(password);
        QueryWrapper<User> queryWrapper=new QueryWrapper();
        queryWrapper.eq("userAccount",account);
        long count = userMapper.selectCount(queryWrapper);
        if(count>0){
            throw new BusinessException(StateCode.PARAMS_ERROR,"账号已重复，请换账号名");
        }
        User user=new User();
        user.setUserAccount(account);
        user.setUserPassword(encryptPassword);
        user.setUserName("ababa");
        user.setUserRole(USER_LOGIN_CODE);
        int count2 = userMapper.insert(user);
        ThrowUtil.throwIf(count2!=1,StateCode.SYSTEM_ERROR,"用户注册失败，系统错误");
        return true;

    }
    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request){
     String account = userLoginRequest.getUserAccount();
     String password = userLoginRequest.getUserPassword();

        if(ObjectUtil.isEmpty(account)||ObjectUtil.isEmpty(password)){
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
//        如果密码长度小于8位，报错
        ThrowUtil.throwIf(password.length()<8,StateCode.PARAMS_ERROR,"密码长度不能小于8位");
//        如果账号长度小于4位，报错
        ThrowUtil.throwIf(account.length()<4,StateCode.PARAMS_ERROR,"账号长度不能小于4位");
//        如果账号不存在，报错
        String encryptPassword=getEncryptPassword(password);
        QueryWrapper<User> queryWrapper=new QueryWrapper();
        queryWrapper.eq("userAccount",account);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if(ObjectUtil.isEmpty(user)){
            throw new BusinessException(StateCode.PARAMS_ERROR,"账号或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_CODE, user);
// 4. 记录用户登录态到 Sa-token，便于空间鉴权时使用，注意保证该用户信息与 SpringSession 中的信息过期时间一致
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_CODE, user);
        LoginUserVO loginUserVO = getLoginUserVO(user);
        return loginUserVO;
    }

    public User getLoginUser(HttpServletRequest request){
        ThrowUtil.throwIf(ObjectUtil.isEmpty(request),StateCode.PARAMS_ERROR);
        User user = (User) request.getSession().getAttribute(USER_LOGIN_CODE);
        if(ObjectUtil.isEmpty(user)){
            throw new BusinessException(StateCode.PARAMS_ERROR,"用户未登录");
        }
        return user;
    }
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user){
        if(user==null){
            return null;
        }
        UserVO userVO=new UserVO();
        BeanUtil.copyProperties(user,userVO);
        return userVO;
    }
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (userList == null) {
            return new ArrayList<>();
        }
//        List<UserVO> arrayList=new ArrayList<>();
//        for (User user : userList) {
//            UserVO userVO=new UserVO();
//            BeanUtil.copyProperties(user,userVO);
//            arrayList.add(userVO);
//        }
        List<UserVO> userVOList = userList.stream().
                map(this::getUserVO).
                collect(Collectors.toList());
        return userVOList;
    }

    @Override
    public boolean userLogout(HttpServletRequest request){
        Object user = request.getSession().getAttribute(USER_LOGIN_CODE);
        ThrowUtil.throwIf(ObjectUtil.isEmpty(user),StateCode.PARAMS_ERROR,"用户未登录");
        request.getSession().removeAttribute(USER_LOGIN_CODE);
        return true;
    }


    @Override
    public User getUserById(long id){
        ThrowUtil.throwIf(id <= 0, StateCode.PARAMS_ERROR);
        User user = userMapper.selectById(id);
        ThrowUtil.throwIf(user == null, StateCode.NOT_FOUND_ERROR,"未找到该用户");
        return user;
    }
    @Override
    public UserVO getUserVOById(long id){
        UserVO userVO=new UserVO();
        User userById = getUserById(id);
        BeanUtil.copyProperties(userById,userVO);
        return userVO;
    }
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(StateCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public String getEncryptPassword(String password){
        final String salt="dragon";
        return DigestUtils.md5DigestAsHex((password+salt).getBytes());
    }

}




